package com.itheima.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.lang.UUID;
import com.alibaba.dubbo.config.annotation.Service;
import com.itheima.dao.MenuDao;
import com.itheima.pojo.Menu;
import com.itheima.service.MenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;


@Service(interfaceClass = MenuService.class)
@Transactional
public class MenuServiceImpl implements MenuService {

    @Autowired
    MenuDao menuDao;


    @Override
    public List<Menu> findAll() {
        //获取一级菜单
        List<Menu>  level1Menus = menuDao.findLevel1();
        if(CollectionUtil.isNotEmpty(level1Menus)){
            //递归查询子菜单
            findChildren(level1Menus);

        }
        return level1Menus;

    }

    @Override
    public void add(Menu menu) {
        menu.setPath(UUID.randomUUID().toString());
        menuDao.add(menu);
    }

    @Override
    public void deleteById(Integer id) {


        menuDao.deleteById(id);
    }

    @Override
    public Menu findById(Integer id) {
        return menuDao.findById(id);

    }

    @Override
    public void edit(Menu menu) {
        menuDao.edit(menu);
    }


    //获取子菜单
    private void findChildren(List<Menu> parents) {
        for (Menu parentMenu : parents) {
            List<Menu> children = menuDao.findChildren(parentMenu.getId());
            if (CollectionUtil.isNotEmpty(children)) {
                findChildren(children);
            }
            parentMenu.setChildren(children);
        }
    }
}
